local BattleLoop = class("BattleLoop",function() return display.newNode() end)


local NewerbattleguideController


BattleLoop.Event_Game_Over = "Event_Game_Over"
BattleLoop.Event_Set_BattleUI_Visible = "Event_Set_BattleUI_Visible"
BattleLoop.Event_Loop_End = "Event_Loop_End"
BattleLoop.Event_Post_Processed = "Event_Post_Processed"
BattleLoop.Event_Battle_Verify = "Event_Battle_Verify"
BattleLoop.Event_Battle_Finished = "Event_Battle_Finished"
BattleLoop.Event_Single_Mode_Check = "Event_Single_Mode_Check"

BattleLoop.Event_Battle_Escape_Tips = "Event_Battle_Escape_Tips"
BattleLoop.Event_Battle_Escape_End_Tips = "Event_Battle_Escape_End_Tips"

BattleLoop.Event_On_Damage = "Event_On_Damage"
BattleLoop.Event_UNIT_TALK = "Event_UNIT_TALK"
BattleLoop.Event_Show_BuffDesc = "Event_Show_BuffDesc"
BattleLoop.Event_Show_Blind = "Event_Show_Blind"

BattleLoop.Event_UNIT_TEAM_MARK = "Event_UNIT_TEAM_MARK"

BattleLoop.Event_UNIT_IMMUNE_BUFF = "Event_UNIT_IMMUNE_BUFF"

BattleLoop.Event_SET_NEXT_UPDATE_TIME = "Event_SET_NEXT_UPDATE_TIME"

BattleLoop.Event_PROJECTILE_BOUNCE = "Event_PROJECTILE_BOUNCE"

BattleLoop.Event_UNIT_REVIVE = "Event_UNIT_REVIVE"

BattleLoop.Event_BATTLE_START = "Event_BATTLE_START"

BattleLoop.Event_LION_BOSS_APPEAR = "Event_LION_BOSS_APPEAR"

BattleLoop.Event_LION_REFRESH_KILLLIST = "Event_LION_REFRESH_KILLLIST"

BattleLoop.Event_BATTLE_ROUND_PREPARE = "Event_BATTLE_ROUND_PREPARE"

BattleLoop.Event_BATTLE_ROUND_SPACE = "Event_BATTLE_ROUND_SPACE"

BattleLoop.Event_SHOW_TIPS = "Event_SHOW_TIPS"

BattleLoop.Event_SOUL_CHANGED = "Event_SOUL_CHANGED"

BattleLoop.Event_DBM_SKILL_HIT= "Event_DBM_SKILL_HIT"

BattleLoop.Event_CLIENT_BATTLE_OVER = "Event_CLIENT_BATTLE_OVER"

local GAME_LENGTH = 40000

local BattleCore_lastState = battle.BattleCore.lastState
local BattleCore_getCurrentTime = battle.BattleCore.getCurrentTime
local BattleCore_progress = battle.BattleCore.progress
local BattleCore_canEscape = battle.BattleCore.canEscape
local BattleCore_enqueue = battle.BattleCore.enqueue
-- local BattleCore_getStates = battle.BattleCore.getStates
-- local BattleCore_getLastReliableTime = battle.BattleCore.getLastReliableTime
local BattleCore =
{
    alive = battle.BattleCore.alive,
    re_getStateVerifys = battle.BattleCore.getStateVerifys,
    getStateVerifyCount = battle.BattleCore.getStateVerifyCount,
    getWonTeamId = battle.BattleCore.getWonTeamId,
    getEntityById = battle.BattleCore.getEntityById,
    escapeAfterTime = battle.BattleCore.escapeAfterTime,
    getBattleTargetString = battle.BattleCore.getBattleTargetString,
    getBattleTimeType = battle.BattleCore.getBattleTimeType,
    getGameLength = battle.BattleCore.getGameLength,
    getMaxReviveTime = battle.BattleCore.getMaxReviveTime,
    getInitReviveTime = battle.BattleCore.getInitReviveTime,
    getLeftReviveTimes = battle.BattleCore.getLeftReviveTimes,
    getDeadTimes = battle.BattleCore.getDeadTimes,
    isOpenDensefog = battle.BattleCore.isOpenDensefog,
    enableAI = battle.BattleCore.enableAI,
    enableClone = battle.BattleCore.enableClone,
    getUnitById = battle.BattleCore.getUnitById,
    getStateByActualTime = battle.BattleCore.getStateByActualTime,
    isSingleMode = battle.BattleCore.isSingleMode,
    getUserCommands = battle.BattleCore.getUserCommands,
    getUnitByUserId = battle.BattleCore.getUnitByUserId,
}

local ProgressResult_getState = battle.ProgressResult.getState
local ProgressResult_getEvents = battle.ProgressResult.getEvents
local ProgressResult_getAccumulator = battle.ProgressResult.getAccumulator
local ProgressResult_getFinished = battle.ProgressResult.getFinished
local ProgressResult_getFinishedReason = battle.ProgressResult.getFinishedReason
local ProgressResult_getIsFastForward = battle.ProgressResult.getIsFastForward
local ProgressResult_getIsRewind = battle.ProgressResult.getIsRewind
local ProgressResult_getBattleResult = battle.ProgressResult.getBattleResult

local State_currentTime = battle.State.currentTime
local State_isEscapeBattle = battle.State.isEscapeBattle
local State_getGameOverDelay = battle.State.getGameOverDelay
local State_getEnsureGameOver = battle.State.getEnsureGameOver
local State_escapeTeamId = battle.State.escapeTeamId
local State_getMVPId = battle.State.getMvpUnitId
local State_isAfterEscapeTime = battle.State.isAfterEscapeTime
local State_getKofRoundLeftTime = battle.State.getKofRoundLeftTime
local State_getKofIndexByTeam = battle.State.getKofIndexByTeam
local State_getScoreByTeamId = battle.State.getScoreByTeamId
local State_getKillList = battle.State.getKillList

local Unit_getSkills = battle.Unit.getSkills
local Unit_getSkill = battle.Unit.getSkill
local Unit_GetItemSkill = battle.Unit.getItemSkill
local Unit_skillInProgress = battle.Unit.skillInProgress
local Unit_withinRangeVision = battle.Unit.withinRangeVision
local Unit_switchAutoBattle = battle.Unit.switchAutoBattle
local Unit_getNextBasicTargetId = battle.Unit.getNextBasicTargetId

local BattleConfig_getUnitConfig = battle.BattleConfig.getUnitConfig
local BattleConfig_getEffectConfig = battle.BattleConfig.getEffectConfig
local BattleConfig_getObjectConfig = battle.BattleConfig.getObjectConfig
local BattleConfig_getSkillConfigs = battle.BattleConfig.getSkillConfigs
local BattleConfig_getBuffConfigs = battle.BattleConfig.getBuffConfigs
local BattleConfig_getBuffConfig = battle.BattleConfig.getBuffConfig
local BattleConfig_getSkillConfig = battle.BattleConfig.getSkillConfig

local EmitParam_getName = battle.EmitParam.getName

local EvtOnHitParam_getHitPar = battle.EvtOnHitParam.getHitPar
local EvtOnHitParam =
{
    getKind = battle.EvtOnHitParam.getKind,
    getSkillId = battle.EvtOnHitParam.getSkillId,
    getTag = battle.EvtOnHitParam.getTag,
    getIsSubSkill = battle.EvtOnHitParam.getIsSubSkill,
    getIsComboSkill = battle.EvtOnHitParam.getIsComboSkill,
    getUid = battle.EvtOnHitParam.getUid,
}

local HitParam_getTime = battle.HitParam.getTime
local HitParam_getCasterId = battle.HitParam.getCasterId
local HitParam_getTargetId = battle.HitParam.getTargetId
local HitParam_getDamage = battle.HitParam.getDamage

local EvtSkillCancelParam_getTime = battle.EvtSkillCancelParam.getTime
local EvtSkillCancelParam_getSkillId = battle.EvtSkillCancelParam.getSkillId
local EvtSkillCancelParam_getSkillUid = battle.EvtSkillCancelParam.getSkillUid
local EvtSkillCancelParam_getCasterId = battle.EvtSkillCancelParam.getCasterId
local EvtSkillCancelParam_getTargetId = battle.EvtSkillCancelParam.getTargetId
local EvtSkillCancelParam_getIsSubSkill = battle.EvtSkillCancelParam.getIsSubSkill
local EvtSkillCancelParam_getIsComboSkill = battle.EvtSkillCancelParam.getIsComboSkill
local EvtSkillCancelParam_getReason = battle.EvtSkillCancelParam.getReason

local EvtOnProjectileBounceParam_getProjectileId = battle.EvtOnProjectileBounceParam.getProjectileId
local EvtOnProjectileBounceParam_getCasterId = battle.EvtOnProjectileBounceParam.getCasterId
local EvtOnProjectileBounceParam_getTargetId = battle.EvtOnProjectileBounceParam.getTargetId
local EvtOnProjectileBounceParam_getPos = battle.EvtOnProjectileBounceParam.getPos

local EvtBuffPhaseParam_getEvent = battle.EvtBuffPhaseParam.getEvent
local EvtBuffPhaseParam_getId = battle.EvtBuffPhaseParam.getId
local EvtBuffPhaseParam_getBearerId = battle.EvtBuffPhaseParam.getBearerId
local EvtBuffPhaseParam_getTime = battle.EvtBuffPhaseParam.getTime
local EvtBuffPhaseParam_getUid = battle.EvtBuffPhaseParam.getUid
local EvtBuffPhaseParam_getCasterId = battle.EvtBuffPhaseParam.getCasterId

local EvtUnitTalkParam_getTime = battle.EvtUnitTalkParam.getTime
local EvtUnitTalkParam_getUnitId = battle.EvtUnitTalkParam.getUnitId
local EvtUnitTalkParam_getContent = battle.EvtUnitTalkParam.getContent

local EvtOnSummonParam_getTime = battle.EvtOnSummonParam.getTime
local EvtOnSummonParam_getCauseKind = battle.EvtOnSummonParam.getCauseKind
local EvtOnSummonParam_getCasterId = battle.EvtOnSummonParam.getCasterId
local EvtOnSummonParam_getCauseId = battle.EvtOnSummonParam.getCauseId
local EvtOnSummonParam_getPosList = battle.EvtOnSummonParam.getPosList

local EvtOnTransformParam_getTime = battle.EvtOnTransformParam.getTime
local EvtOnTransformParam_getCasterId = battle.EvtOnTransformParam.getCasterId
local EvtOnTransformParam_getSkillId = battle.EvtOnTransformParam.getSkillId

local EvtOnFlagParam_getTime = battle.EvtOnFlagParam.getTime
local EvtOnFlagParam_getTargetId = battle.EvtOnFlagParam.getTargetId
local EvtOnFlagParam_getCasterId = battle.EvtOnFlagParam.getCasterId
local EvtOnFlagParam_getFlagId = battle.EvtOnFlagParam.getFlagId

local EvtOnImmuneParam_getTime = battle.EvtOnImmuneParam.getTime
local EvtOnImmuneParam_getCasterId = battle.EvtOnImmuneParam.getCasterId
local EvtOnImmuneParam_getTargetId = battle.EvtOnImmuneParam.getTargetId
local EvtOnImmuneParam_getTag = battle.EvtOnImmuneParam.getTag

local EvtTipsParam_getTime = battle.EvtTipsParam.getTime
local EvtTipsParam_getUnitId = battle.EvtTipsParam.getUnitId
local EvtTipsParam_getTipsType = battle.EvtTipsParam.getTipsType
local EvtTipsParam_getTargetUnitId = battle.EvtTipsParam.getTargetUnitId

local EvtOnReviveParam_getTime = battle.EvtOnReviveParam.getTime
local EvtOnReviveParam_getTargetId = battle.EvtOnReviveParam.getTargetId
local EvtOnReviveParam_getPos = battle.EvtOnReviveParam.getPos

local EvtOnBattleStartParam_getTime = battle.EvtOnBattleStartParam.getTime
local EvtOnRoundStartParam_getTime = battle.EvtOnRoundStartParam.getTime

local EvtOnRoundPrepareParam_getTime = battle.EvtOnRoundPrepareParam.getTime

local SkillConfig_isBasicAttack = battle.SkillConfig.isBasicAttack
local Battle_SkillConfig = battle.SkillConfig
local SkillConfig_targetSelectionNeeded = battle.SkillConfig.targetSelectionNeeded

local BuffConfig_getDisplayDesc = battle.BuffConfig.getDisplayDesc
local BuffConfig_getDisplaySort = battle.BuffConfig.getDisplaySort
local BuffConfig_specialEffect = battle.BuffConfig.specialEffect

local EventParCache = {}

local DebugMode = false
local function debugLog(...)
    if DebugMode then
        print("[battle]",...)
    end
end

function BattleLoop.create(battleCore, battleModel)
    local battleLoop = BattleLoop.new({battleCore = battleCore, battleModel = battleModel,})
    return battleLoop
end

function BattleLoop:createUnits()
    if self.mBattleCore then
        debugLog("-------------BattleLoop:createUnits------------")
        local unitIds = self.mBattleCore:createUnitsByDesc(BattleCore_lastState(self.mBattleCore))
        return unitIds
    end
    return nil
end

function BattleLoop:ctor(params)
    self.mBattleCore = params.battleCore
    self.mBattleModel = params.battleModel

    local function callBack(time,command,result)
        self:dispatchEvent(BattleLoop.Event_Post_Processed,{time = time, command = command, result = result})
    end

    local signal = self:getProcessedSignal()
    if signal then
        signal:addProcessedCmd(callBack)
    end

    --todo
    self.onHitSignal = display.newNode()
    self:addChild(self.onHitSignal)
    cc(self.onHitSignal):addComponent("components.behavior.SimpleEvent"):exportMethods()

    self.skillCancelSignal = display.newNode()
    self:addChild(self.skillCancelSignal)
    cc(self.skillCancelSignal):addComponent("components.behavior.SimpleEvent"):exportMethods()

    self.buffSignal = display.newNode()
    self:addChild(self.buffSignal)
    cc(self.buffSignal):addComponent("components.behavior.SimpleEvent"):exportMethods()

    self.onSummonSignal = display.newNode()
    self:addChild(self.onSummonSignal)
    cc(self.onSummonSignal):addComponent("components.behavior.SimpleEvent"):exportMethods()

    self.onTransformSignal = display.newNode()
    self:addChild(self.onTransformSignal)
    cc(self.onTransformSignal):addComponent("components.behavior.SimpleEvent"):exportMethods()

    self:initResConfig()

    cc(self):addComponent("components.behavior.SimpleEvent"):exportMethods()

    self._callbackDict={}

    self:enableNodeEvents()

    self._startClientGameOver = false
    --dump("start create battle loop ")
    -- 新手战斗引导是否结束标记、默认没有
    NewerbattleguideController = app:getInst( "NewerbattleguideController" )
    self._newerBattleGuideEndedFlag = NewerbattleguideController:isNewerBattleGuideEnded() or false
    app:addCustomEventListener( Constant.BattleNewerGuideEndFlag, function()
        print( " ---------------->>>>>>>> BattleLoop _newerBattleGuideEndedFlag true" )
        self._newerBattleGuideEndedFlag = true
    end, self )
end

function BattleLoop:getProcessedSignal()
    if self.mBattleCore then
        local signal = self.mBattleCore:getProcessedSignal()
        return signal
    end
    return nil
end

function BattleLoop:getRewindedSignal()
    if self.mBattleCore then
        local signal = self.mBattleCore:getRewindedSignal()
        return signal
    end
    return nil
end

function BattleLoop:getFastForwardSignal()
    if self.mBattleCore then
        local signal = self.mBattleCore:getFastForwardSignal()
        return signal
    end
    return nil
end

function BattleLoop:getOnHitSignal()
    return self.onHitSignal
end

function BattleLoop:getSkillCancelSignal()
    return self.skillCancelSignal
end

function BattleLoop:getBuffSignal()
    return self.buffSignal
end

function BattleLoop:getOnSummonSignal()
    return self.onSummonSignal
end

function BattleLoop:getOnTransformSignal()
    return self.onTransformSignal
end

function BattleLoop:onEnter()
    debugLog("--------BattleLoop:onEnter----------")
    EventParCache = {}
end

function BattleLoop:removeScriptHandlers(target)
    if target then
        local handlers
        if target.getScriptHandlers then
            handlers = target:getScriptHandlers()
        end
        if handlers then
            for i = 1, #handlers do
                custom.toluafixRemoveFunctionByRefid(handlers[i])
            end
        end
    end
end

function BattleLoop:onExit()
    debugLog("--------BattleLoop:onExit----------")
    EventParCache = {}
    -- Clear script handler register in C++
    self:removeScriptHandlers(self:getProcessedSignal())
    self:removeScriptHandlers(self:getRewindedSignal())
    self:removeScriptHandlers(self:getFastForwardSignal())

    self:removeScriptHandlers(battle.NormalSkillFsm:Instance())
    self:removeScriptHandlers(battle.SubSkillFsm:Instance())
    battle.NormalSkillFsm:Instance():off()
    battle.SubSkillFsm:Instance():off()

    if self.mBattleCore then
        self.mBattleCore:release()
        self.mBattleCore = nil
    end

    self:removeAllEventListeners()

    self.onHitSignal:removeAllEventListeners()
    self.skillCancelSignal:removeAllEventListeners()
    self.buffSignal:removeAllEventListeners()
    self.onSummonSignal:removeAllEventListeners()
    self.onTransformSignal:removeAllEventListeners()

    self.onHitSignal = nil
    self.skillCancelSignal = nil
    self.buffSignal = nil
    self.onSummonSignal = nil
    self.onTransformSignal = nil
end

function BattleLoop:initResConfig()
    self.mBattleConfig = battle.BattleConfig:getInstance()
end

function BattleLoop:getUnitConfig(unitId)
    if self.mBattleConfig then
        return BattleConfig_getUnitConfig(self.mBattleConfig, unitId) --self.mBattleConfig:getUnitConfig(unitId)
    end
    return nil
end

function BattleLoop:getTimeMonsterNpcId(battleTimes)
    if self.mBattleConfig then
        return self.mBattleConfig:getSceneConfigTimeMonsterID(battleTimes)
    end
    return 0
end

function BattleLoop:getEffectConfig(effectId)
    if self.mBattleConfig then
        return BattleConfig_getEffectConfig(self.mBattleConfig, effectId) --self.mBattleConfig:getEffectConfig(effectId)
    end
    return nil
end

function BattleLoop:getObjectConfig(projectileResId)
    if self.mBattleConfig then
        return BattleConfig_getObjectConfig(self.mBattleConfig, projectileResId) --self.mBattleConfig:getObjectConfig(projectileResId)
    end
    return nil
end

function BattleLoop:getSkillConfigs()
    if self.mBattleConfig then
        return BattleConfig_getSkillConfigs(self.mBattleConfig) --self.mBattleConfig:getSkillConfigs()
    end
    return nil
end

function BattleLoop:getBuffConfigs()
    if self.mBattleConfig then
        return BattleConfig_getBuffConfigs(self.mBattleConfig) --self.mBattleConfig:getBuffConfigs()
    end
    return nil
end

function BattleLoop:getBuffConfig(buffId)
    if self.mBattleConfig then
        return BattleConfig_getBuffConfig(self.mBattleConfig, buffId) --self.mBattleConfig:getBuffConfig(buffId)
    end
    return nil
end

function BattleLoop:getSkillConfig(skillId)
    if self.mBattleConfig then
        return BattleConfig_getSkillConfig(self.mBattleConfig, skillId) --self.mBattleConfig:getSkillConfig(skillId)
    end
    return nil
end

function BattleLoop:getBattleTargetString(teamId)
    if self.mBattleCore then
        return BattleCore.getBattleTargetString(self.mBattleCore, teamId)
    end
    return nil
end

function BattleLoop:getGameLength()
    if self.mBattleCore then
        return BattleCore.getGameLength(self.mBattleCore)
    end
    return 0
end

function BattleLoop:isOpenDenseFog()
    if self.mBattleCore then
        return BattleCore.isOpenDensefog(self.mBattleCore)
    end
    return false
end

function BattleLoop:getMaxReviveTimes(teamId)
    if self.mBattleCore then
        return BattleCore.getMaxReviveTime(self.mBattleCore, teamId)
    end
    return 0
end

function BattleLoop:getInitReviveTimes(teamId)
    if self.mBattleCore then
        return BattleCore.getInitReviveTime(self.mBattleCore, teamId)
    end
    return 0
end

function BattleLoop:getLeftReviveTimes(teamId)
    if self.mBattleCore then
        return BattleCore.getLeftReviveTimes(self.mBattleCore, teamId)
    end
    return 0
end

function BattleLoop:getDeadTimes(teamId)
    if self.mBattleCore then
        return BattleCore.getDeadTimes(self.mBattleCore, teamId)
    end
    return 0
end

function BattleLoop:isBattleTimeCountDown()
    if self.mBattleCore then
        return BattleCore.getBattleTimeType(self.mBattleCore) == 0
    end
    return false
end

function BattleLoop:getMvpUnitId()
    if self.mBattleModel:isPvpBattle() or self.mBattleModel:isMeleeBattle() then
        if cc.isAlive(self.currentState) then
            return State_getMVPId(self.currentState)
        end
    end
end

function BattleLoop:getScoreByTeamId(teamId)
    return State_getScoreByTeamId(self.currentState,teamId)
end

function BattleLoop:isAfterEscapeTime()
    return State_isAfterEscapeTime(self.currentState)
end

function BattleLoop:getKofRoundLeftTime()
    return State_getKofRoundLeftTime(self.currentState)
end

function BattleLoop:getKofIndexByTeam(teamId)
    return State_getKofIndexByTeam(self.currentState, teamId)
end

function BattleLoop:getKillList()
    return State_getKillList(self.currentState)
end

function BattleLoop:start(currentTime, passedTime)
    debugLog("-------BattleLoop:start---------")
    debugLog("currentTime:", currentTime)
    debugLog("passedTime:", passedTime)

    self.accumulator = 0
    self.currentTime = currentTime - (passedTime/1000.0)
    self._startClientGameOver = false
    if passedTime > 0 then
        self.isNeedPass = true
    end
    if self.mBattleCore then
        self.previousState = BattleCore_lastState(self.mBattleCore)
        self.currentState = self.previousState
        self.events = {}
        self.finished = false
        self.finishedReason = Enums.FinishedReason.FR_None

        if BattleCore.isSingleMode(self.mBattleCore) then
            BattleCore.enableAI(self.mBattleCore,true)
            BattleCore.enableClone(self.mBattleCore,false)

            local msg = BattleManager:getSingleModeStartData()
			local units = msg.desc.units

            local pu
			for i, v in ipairs( units ) do
				if v.kind == "UnitKind_Player" and v.userBaseInfo.uid < 0 then
					pu = BattleCore.getUnitById(self.mBattleCore, v.unitModelId)
					Unit_switchAutoBattle(pu, true, -1)
				end
			end
        end
    end
end

function BattleLoop:loop(currentTime, dt)
    self.isRewind = false
    self.isFastForward = false
    if self.finished then
        return
    end

    if BattleManager:getPauseBattleDelta() > 0 then
        self.currentTime = self.currentTime + BattleManager:getPauseBattleDelta()
        BattleManager:clearPauseBattleDelta()
    end
    local timeLapsed = currentTime - self.currentTime
    local logicFrameTime = math.floor(timeLapsed*1000)
    self.currentTime = currentTime
    self.accumulator = self.accumulator + logicFrameTime

    local isNeedPass = self.isNeedPass
    self.isNeedPass = false

    if self.mBattleCore then
        -- local states = BattleCore_getStates(self.mBattleCore)
        -- local lastReliableTime = BattleCore_getLastReliableTime(self.mBattleCore)
        -- release_print("------------> loop start --------- ", self.currentTime)
        -- release_print("============> accumulator:", self.accumulator, "logicFrameTime:", logicFrameTime)
        -- release_print("============> states count:", #states)
        -- release_print("============> lastReliableTime:", lastReliableTime)
        self.previousState = BattleCore_lastState(self.mBattleCore)
        local battleCoreTime = BattleCore_getCurrentTime(self.mBattleCore)
        -- release_print("============> battleCoreTime:", battleCoreTime)

        local accumulator = self.accumulator
        self:dispatchEvent("Event_SET_NEXT_UPDATE_TIME",battleCoreTime + Constant.BattleSliceTime)

        -- C++ battle engine update.
        local progressResult = BattleCore_progress(self.mBattleCore, accumulator)

        -- print("------------> loop end --------- ", self.currentTime)
        self.currentState = ProgressResult_getState(progressResult)
        self.events = ProgressResult_getEvents(progressResult)
        self.isFastForward = ProgressResult_getIsFastForward(progressResult)
        self.isRewind = ProgressResult_getIsRewind(progressResult)
        if (isNeedPass or self.isFastForward) and not self:isSingleMode() then
            --如果是快进，则忽略一些事件
            local events = {}
            local curTime = State_currentTime(self.currentState)
            for k,event in pairs(self.events) do
                local eveName = EmitParam_getName(event)
                local isAdd = false
                local time = 0
                if eveName == "skill-cancelled" then
                    --保留技能取消事件
                    isAdd = true
                    time = EvtSkillCancelParam_getTime(event) --event:getTime()
                elseif eveName == "buff-phase" then
                    time = EvtBuffPhaseParam_getTime(event) --event:getTime()
                    --保留buff结束事件
                    local eventStr = EvtBuffPhaseParam_getEvent(event) --event:getEvent()
                    if eventStr == "enter-buff" or eventStr == "exit-buff" then
                        isAdd = true
                    end
                elseif eveName == "on-bounce-projectile" then
                    --弹道反弹
                    isAdd = true
                elseif eveName == "on-transform" then
                    isAdd = true
                elseif eveName == "on-battle-start" then
                    isAdd = true
                elseif eveName == "on-round-start" then
                    isAdd = true
                elseif eveName == "on-round-prepare" then
                    isAdd = true
                elseif eveName == "on-round-space" then
                    isAdd = true
                elseif eveName == "on-boss-appear" then
                    isAdd = true
                elseif eveName == "on-refresh-killlist" then
                    isAdd = true
                elseif eveName == "on-hit" then
                    local hitParam = EvtOnHitParam_getHitPar(event)
                    time = HitParam_getTime(hitParam)
                elseif eveName == "unit-talk" then
                    time = EvtUnitTalkParam_getTime(event)
                elseif eveName == "on-summon" then
                    time = EvtOnSummonParam_getTime(event)
                elseif eveName == "on-flag" then
                    time = EvtOnFlagParam_getTime(event)
                elseif eveName == "on-revive" then
                    time = EvtOnReviveParam_getTime(event)
                elseif eveName == "tips" then
                    time = EvtTipsParam_getTime(event)
                elseif eveName == "unit-soulchanged" then
                    isAdd = true
                end

                -- if curTime == time then
                --     --保留最后一帧事件
                --     isAdd = true
                -- end

                if math.abs(curTime - time) <= Constant.BattleEffectRetainTime then
                    isAdd = true
                end

                if isAdd then
                    table.insert(events,event)
                end
            end
            self.events = events
        end

        self.accumulator = ProgressResult_getAccumulator(progressResult)
        -- debugLog("---------progressResult.accumulator:"..ProgressResult_getAccumulator(progressResult))
        self.finished = ProgressResult_getFinished(progressResult)
        self.finishedReason = ProgressResult_getFinishedReason(progressResult)

        local ensureGameOver = State_getEnsureGameOver(self.currentState)
        if ensureGameOver then
            if not self.isSendVerifyMsg then
                self.isSendVerifyMsg = true
                --获取验证数值
                -- local datas = {}
                -- local verifys =  BattleCore_getStateVerifys(self.mBattleCore) -- self.mBattleCore:getStateVerifys()
                -- debugLog("----------verifys count:",#verifys)
                -- if verifys then
                --     for k,verify in pairs(verifys) do
                --         -- debugLog("-------------k:",k)
                --         if verify then
                --             local data = {}
                --             data.currentTime = verify:currentTime()
                --             -- debugLog("---------currentTime:",data.currentTime)
                --             data.units = {}
                --             local unitVerifys = verify:getUnitVerifys()
                --             if unitVerifys then
                --                 for _,unitVerify in pairs(unitVerifys) do
                --                     local unit = {}
                --                     unit.id = unitVerify:id()
                --                     -- debugLog("---------unit.id:",unit.id)
                --                     unit.hp = unitVerify:hp()
                --                     -- debugLog("---------unit.hp:",unit.hp)
                --                     unit.pos = unitVerify:pos()
                --                     -- debugLog("---------unit.pos:",unit.pos)
                --                     table.insert(data.units, unit)
                --                 end
                --             end
                --             table.insert(datas, data)
                --         end
                --     end
                -- end
                -- debugLog("----------datas count:",#datas)
                local winTeamId = BattleCore.getWonTeamId(self.mBattleCore)
                local verifyCount = BattleCore.getStateVerifyCount(self.mBattleCore)
                debugLog("----------verify count:", verifyCount)
                EventParCache.count = verifyCount
                EventParCache.wonTeam = winTeamId
                self:dispatchEvent(BattleLoop.Event_Battle_Verify,EventParCache)
            end
        end

        -- local gameOverDelay = State_getGameOverDelay(self.currentState)
        -- debugLog("=============BattleLoop:loop==========:",gameOverDelay)
        if self.finished then
            EventParCache.commands = BattleCore.getUserCommands(self.mBattleCore)
            EventParCache.result = ProgressResult_getBattleResult(progressResult)
            EventParCache.finishedReason = self.finishedReason
            self:dispatchEvent(BattleLoop.Event_Battle_Finished, EventParCache)

            if self.finishedReason == Enums.FinishedReason.FR_Timeout then
                if not (self.mBattleModel:isPvpBattle() or self.mBattleModel:isMeleeBattle() or self.mBattleModel:isLionBattle() or self:isSingleMode()) then
                    app:popMessage("fight_battle_error_13", nil, nil, Enums.ToastTag.battle)
                end
            elseif self.finishedReason == Enums.FinishedReason.FR_Escape then
                local escapeTeamId = State_escapeTeamId(self.currentState) -- self.currentState:escapeTeamId()
                EventParCache.escapeTeamId = escapeTeamId
                self:dispatchEvent(BattleLoop.Event_Battle_Escape_End_Tips,EventParCache)
            end

            self:stop()
        else
            -- self:fireEvents(self.events)

            --如果逃跑，提示
            if State_isEscapeBattle(self.currentState) then
                if not self.isShowEscapeTips then
                    self.isShowEscapeTips = true
                    local escapeTeamId = State_escapeTeamId(self.currentState)
                    EventParCache.escapeTeamId = escapeTeamId
                    self:dispatchEvent(BattleLoop.Event_Battle_Escape_Tips,EventParCache)
                end
            end
            local isClientGameOver = self.isGameOver
            self:checkGameOver()

            if self.isGameOver and not isClientGameOver and not self._startClientGameOver then
                self._startClientGameOver = true
                self:dispatchEvent(BattleLoop.Event_CLIENT_BATTLE_OVER)
            end
        end
    end

end

local BattleLoop_loop = BattleLoop.loop
function BattleLoop:tick_(dt, currentTime)
    BattleLoop_loop(self, currentTime, dt)
end

function BattleLoop:fireEvents(events)
    local isNeedRefreshKillList = false
    if not events then
        print( " ------------>>>>>>> BattleLoop:fireEvents no events" )
        return
    end
    for k,event in pairs(events) do
        local eveName = EmitParam_getName(event)
        if eveName == "on-hit" then
            --debugLog("----------toId:",event:getTargetId())
            local isBasicAttack = false
            local skillId
            local kind = EvtOnHitParam.getKind(event)
            local skillIdOrProjectileTag
            local temp = EvtOnHitParam.getSkillId(event)
            if kind == Enums.EntityKind.EKind_Skill then
                skillIdOrProjectileTag = temp
                skillId = skillIdOrProjectileTag
            elseif kind == Enums.EntityKind.EKind_Projectile then
                skillIdOrProjectileTag = EvtOnHitParam.getTag(event)
                skillId = temp
            elseif kind == Enums.EntityKind.EKind_Buff then
                -- skillIdOrProjectileTag = event:getBuffId()
                skillIdOrProjectileTag = temp
                skillId = skillIdOrProjectileTag
            end

            if skillId then
                local skillCfg = self:getSkillConfig(skillId)
                if skillCfg then
                    if SkillConfig_isBasicAttack(skillCfg) then
                        isBasicAttack = true
                    end
                end

                if not self._newerBattleGuideEndedFlag then -- 新手战引导未结束？
--                    print( " ---------------->>>>>>>> 新手战引导 on-hit", skillId )
                    NewerbattleguideController:triggerBattleGuideEvent( skillId, "on-hit" )
                end
            end
            local hitParam = EvtOnHitParam_getHitPar(event)
            self:dispatchEvent(BattleLoop.Event_On_Damage, event, isBasicAttack)

            local casterId = HitParam_getCasterId(hitParam)
            local targetId = HitParam_getTargetId(hitParam)
            local isSubSkill = EvtOnHitParam.getIsSubSkill(event)
            local isComboSkill = EvtOnHitParam.getIsComboSkill(event)
            local time = HitParam_getTime(hitParam)
            local damage = HitParam_getDamage(hitParam)
            local uid = EvtOnHitParam.getUid(event)
            EventParCache.t = time
            EventParCache.kind = kind
            EventParCache.skillIdOrProjectileTag = skillIdOrProjectileTag
            EventParCache.skillOrProjectileUid = uid
            EventParCache.casterId = casterId
            EventParCache.targetId = targetId
            EventParCache.isSubSkill = isSubSkill
            EventParCache.isComboSkill = isComboSkill
            EventParCache.damage = damage
            self.onHitSignal:dispatchEvent("EVENT_ON_HIT",EventParCache)

            --dbm
            self:dispatchEvent(BattleLoop.Event_DBM_SKILL_HIT, {skillId = skillId,targetId = targetId})

        -- elseif eveName == "on-projectile-hit" then
        --     --debugLog("----------toId:",event:getTargetId())
        --     -- debugLog("-------------fireEvents----on-projectile-hit-------")
        --     local hitParam = event:getHitPar()
        --     self:dispatchEvent({name = BattleLoop.Event_On_Damage, params = hitParam})
        --     self.onHitSignal:dispatchEvent({name = "EVENT_ON_PROJECTILE_HIT", t = hitParam:getTime(), fromId = hitParam:getCasterId(), toId = hitParam:getTargetId(), projectileTag = event:getTag(), damage = hitParam:getDamage()})
        -- elseif eveName == "on-settlement-hit" then
        --     --debugLog("----------toId:",event:getTargetId())
        --     local hitParam = event:getHitPar()
        --     self:dispatchEvent({name = BattleLoop.Event_On_Damage, params = hitParam})
        --     self.onHitSignal:dispatchEvent({name = "EVENT_ON_SETTLEMENT_HIT", t = hitParam:getTime(), skillUid = event:getSkillUid(), skillId = event:getSkillId(), fromId = hitParam:getCasterId(), toId = hitParam:getTargetId(), damage = hitParam:getDamage()})
        elseif eveName == "skill-cancelled" then
            local casterId = EvtSkillCancelParam_getCasterId(event)
            local targetId = EvtSkillCancelParam_getTargetId(event)
            local skillId = EvtSkillCancelParam_getSkillId(event)
            local skillUid = EvtSkillCancelParam_getSkillUid(event)
            local isSubSkill = EvtSkillCancelParam_getIsSubSkill(event)
            local isComboSkill = EvtSkillCancelParam_getIsComboSkill(event)
            local reason = EvtSkillCancelParam_getReason(event)
            EventParCache.skillId = skillId
            EventParCache.skillUid = skillUid
            EventParCache.casterId = casterId
            EventParCache.targetId = targetId
            EventParCache.isSubSkill = isSubSkill
            EventParCache.isComboSkill = isComboSkill
            EventParCache.reason = reason
            self.skillCancelSignal:dispatchEvent("EVENT_SKILL_CANCEL",EventParCache)
        elseif eveName == "on-bounce-projectile" then
            local casterId = EvtOnProjectileBounceParam_getCasterId(event)
            local targetId = EvtOnProjectileBounceParam_getTargetId(event)
            local projectileId = EvtOnProjectileBounceParam_getProjectileId(event)
            local pos = EvtOnProjectileBounceParam_getPos(event)
            EventParCache.projectileId = projectileId
            EventParCache.casterId = casterId
            EventParCache.targetId = targetId
            EventParCache.pos = pos
            self:dispatchEvent(BattleLoop.Event_PROJECTILE_BOUNCE,EventParCache)
        elseif eveName == "buff-phase" then
            local bearerId = EvtBuffPhaseParam_getBearerId(event)
            local casterId = EvtBuffPhaseParam_getCasterId(event)
            local phase = EvtBuffPhaseParam_getEvent(event)
            -- print("----------fireEvents eveName:",eveName, "MyId", self.mBattleModel:getControlledEntityId(), " casterId", casterId, " bearerId", bearerId, " phase", phase)
            local buffId = EvtBuffPhaseParam_getId(event)
            if phase == "enter-buff" then
                local buffCfg = self:getBuffConfig(buffId)
                if buffCfg then
                    local displayDesc = BuffConfig_getDisplayDesc(buffCfg)
                    local displaySort = BuffConfig_getDisplaySort(buffCfg)
                    if displayDesc and string.len(displayDesc) > 0 then
                        --debugLog("===enter-buff displayDesc:",displayDesc)
                        EventParCache.buffId = buffId
                        EventParCache.casterId = casterId
                        EventParCache.bearerId = bearerId
                        EventParCache.displayDesc = displayDesc
                        EventParCache.displaySort = displaySort
                        self:dispatchEvent(BattleLoop.Event_Show_BuffDesc,EventParCache)
                    end

                    local specialEffect = BuffConfig_specialEffect(buffCfg)
                    if specialEffect == Enums.BuffEffectsLogic.BE_Blind and self.mBattleModel:getControlledEntityId() == bearerId then
                        --如果自己被致盲
                        self:dispatchEvent(BattleLoop.Event_Show_Blind)
                    end

                    --dbm
                    self:dispatchEvent(BattleLoop.Event_DBM_SKILL_HIT, {skillId = buffId,targetId = bearerId})
                end
            end

            local t = EvtBuffPhaseParam_getTime(event)
            local buffUid = EvtBuffPhaseParam_getUid(event)
            EventParCache.t = t
            EventParCache.buffId = buffId
            EventParCache.buffUid = buffUid
            EventParCache.casterId = casterId
            EventParCache.bearerId = bearerId
            EventParCache.phase = phase
            self.buffSignal:dispatchEvent("EVENT_ON_BUFF",EventParCache)
        elseif eveName == "unit-talk" then
            --debugLog("================unit-talk")
            local time = EvtUnitTalkParam_getTime(event)
            local unitId = EvtUnitTalkParam_getUnitId(event)
            local text = EvtUnitTalkParam_getContent(event)
            self:dispatchEvent(BattleLoop.Event_UNIT_TALK,time,unitId,text)
        elseif eveName == "on-summon" then
            local causeKind = EvtOnSummonParam_getCauseKind(event)
            local time = EvtOnSummonParam_getTime(event)
            local casterId = EvtOnSummonParam_getCasterId(event)
            local causeId = EvtOnSummonParam_getCauseId(event)
            local posList = EvtOnSummonParam_getPosList(event)
            --debugLog("========================event====onSummon=====on-summon=======================")
            EventParCache.t = time
            EventParCache.causeId = causeId
            EventParCache.causeKind = causeKind
            EventParCache.casterId = casterId
            EventParCache.posList = posList
            self.onSummonSignal:dispatchEvent("EVENT_ON_SUMMON",EventParCache)
        elseif eveName == "on-transform" then
            local time = EvtOnTransformParam_getTime(event)
            local skillId = EvtOnTransformParam_getSkillId(event)
            local casterId = EvtOnTransformParam_getCasterId(event)
            EventParCache.t = time
            EventParCache.skillId = skillId
            EventParCache.casterId = casterId
            self.onTransformSignal:dispatchEvent("EVENT_ON_TRANSFORM",EventParCache)
        elseif eveName == "on-flag" then
            local time = EvtOnFlagParam_getTime(event)
            local targetId = EvtOnFlagParam_getTargetId(event)
            local casterId = EvtOnFlagParam_getCasterId(event)
            local flagId = EvtOnFlagParam_getFlagId(event)
            EventParCache.time = time
            EventParCache.targetId = targetId
            EventParCache.casterId = casterId
            EventParCache.flagId = flagId
            self:dispatchEvent(BattleLoop.Event_UNIT_TEAM_MARK,EventParCache)
        elseif eveName == "on-immune" then
            local casterId = EvtOnImmuneParam_getCasterId(event)
            local targetId = EvtOnImmuneParam_getTargetId(event)
            local time = EvtOnImmuneParam_getTime(event)
            local tag = EvtOnImmuneParam_getTag(event)
            EventParCache.time = time
            EventParCache.casterId = casterId
            EventParCache.targetId = targetId
            EventParCache.tag = tag
            self:dispatchEvent(BattleLoop.Event_UNIT_IMMUNE_BUFF,EventParCache)
        elseif eveName == "on-revive" then
            local time = EvtOnReviveParam_getTime(event)
            local targetId = EvtOnReviveParam_getTargetId(event)
            local pos = EvtOnReviveParam_getPos(event)

            EventParCache.time = time
            EventParCache.targetId = targetId
            EventParCache.pos = pos
            self:dispatchEvent(BattleLoop.Event_UNIT_REVIVE,EventParCache)
        elseif eveName == "on-battle-start" then
            if not self.mBattleModel:isKofBattle() then
                local time = EvtOnBattleStartParam_getTime(event)
                EventParCache.time = time
                self:dispatchEvent(BattleLoop.Event_BATTLE_START,EventParCache)
            end
        elseif eveName == "on-round-start" then
            local time = EvtOnRoundStartParam_getTime(event)
            EventParCache.time = time
            self:dispatchEvent(BattleLoop.Event_BATTLE_START,EventParCache)
        elseif eveName == "on-round-prepare" then
            local time = EvtOnRoundPrepareParam_getTime(event)
            local round = event:getRound()
            EventParCache.time = time
            EventParCache.round = round
            self:dispatchEvent(BattleLoop.Event_BATTLE_ROUND_PREPARE,EventParCache)
        elseif eveName == "on-round-space" then
            -- print("============on-round-space=================")
            self:dispatchEvent(BattleLoop.Event_BATTLE_ROUND_SPACE,EventParCache)
        elseif eveName == "on-refresh-killlist" then
            isNeedRefreshKillList = true --使用变量，减少快进时调用此时
        elseif eveName == "on-boss-appear" then
            local time = event:getTime()
            EventParCache.time = time
            self:dispatchEvent(BattleLoop.Event_LION_BOSS_APPEAR,EventParCache)
        elseif eveName == "tips" then
            local time = event:getTime()
            local tipsType = event:getTipsType()
            local unitId = event:getUnitId()
            local targetUnitId = event:getTargetUnitId()
            local assits = event:getAssists()
            local continuousKill = event:getContinuousKill()
            EventParCache.time = time
            EventParCache.tipsType = tipsType
            EventParCache.unitId = unitId
            EventParCache.targetUnitId = targetUnitId
            EventParCache.assits = assits
            EventParCache.continuousKill = continuousKill

            self:dispatchEvent(BattleLoop.Event_SHOW_TIPS,EventParCache)
        elseif eveName == "unit-soulchanged" then
            local time = event:getTime()
            local unitId = event:getUnitId()
            local oldSoul = event:getOldSoul()
            local newSoul = event:getNewSoul()
            EventParCache.time = time
            EventParCache.unitId = unitId
            EventParCache.oldSoul = oldSoul
            EventParCache.newSoul = newSoul
            self:dispatchEvent(BattleLoop.Event_SOUL_CHANGED,EventParCache)
        end
    end

    if isNeedRefreshKillList then
        self:dispatchEvent(BattleLoop.Event_LION_REFRESH_KILLLIST)
    end
end

local BattleLoop_fireEvents = BattleLoop.fireEvents
function BattleLoop:processEvents()
    if not self.finished then
        BattleLoop_fireEvents(self, self.events)
    end
end

function BattleLoop:getCurrentState()
    return self.currentState
end

function BattleLoop:makeClientCommand(unitId, seq, cmdId, inputData)
    if self.mBattleCore then
        local cmd = battle.Command:create(
            unitId,
            seq,
            cmdId,
            inputData.skill,
            Enums.TargetType.TargetType_Id, --1 目标类型为id
            inputData.target or 0,
            self:getBattleLogicTime(),
            0
        )
        return cmd
    end
    return nil
end

function BattleLoop:enqueue(cmd)
    if self.mBattleCore then
        BattleCore_enqueue(self.mBattleCore, cmd)
    end
end

function BattleLoop:syncState(protoStates)
    if self.mBattleCore then
        local syncedStateTimes
        for time, protoState in pairs(protoStates) do
            local state = BattleCore.getStateByActualTime(self.mBattleCore, time)
            if state then
--                debugLog("=========================BattleLoop:syncState====================== ", protoState.time)
                syncedStateTimes = syncedStateTimes or {}
                table.insert(syncedStateTimes, time)
                local logicUnit
                for i, unit in ipairs(protoState.units) do
                    logicUnit = state:getUnitById(unit.id)
                    if logicUnit and logicUnit:hp() > 0 then
--                        debugLog(">>>>> id:", unit.id, "  setHp:", unit.hp, "  old hp:", logicUnit:hp())
                        logicUnit:setHp(unit.hp, false)
                    end
                end
            end
        end
        return syncedStateTimes
    end
end

function BattleLoop:canEscape()
    --debugLog("===========BattleLoop:canEscape=========")
    if self.mBattleCore then
        return BattleCore_canEscape(self.mBattleCore)
    end
end

function BattleLoop:escapeAfterTime()
    if self.mBattleCore then
        return BattleCore.escapeAfterTime(self.mBattleCore)
    end
end

function BattleLoop:getEntityById(id)
    if self.mBattleCore then
        -- debugLog("-------getEntityById:"..id)
        return BattleCore.getEntityById(self.mBattleCore, id)
    end
    return nil
end

function BattleLoop:getEntitySkills(id)
    local entity = self:getEntityById(id)
    if entity then
        return Unit_getSkills(entity)
    end
    return nil
end

function BattleLoop:getItemSkillByInstanceId(playerId,skillId)
    local unit = self:getEntityById(playerId)
    if unit then
        local skill = Unit_GetItemSkill(unit, skillId)
        return skill
    end
    return nil
end

function BattleLoop:getEntitySkillInProgress(id)
    local entity = self:getEntityById(id)
    if entity then
        return Unit_skillInProgress(entity)
    end
    return nil
end

function BattleLoop:getEntityNextBasicTargetId(id)
    local entity = self:getEntityById(id)
    if entity then
        return Unit_getNextBasicTargetId(entity)
    end
    return 0
end

function BattleLoop:isInRangeVision(fromId, targetId)
    -- debugLog("=========setSkillTarget===:",targetId)
    local unit = self:getEntityById(fromId)
    local target = self:getEntityById(targetId)
    if unit ~= nil then
        return Unit_withinRangeVision(unit, target)
    end
    return true
end

function BattleLoop:getEntitySkillById(playerId,skillId)
    local unit = self:getEntityById(playerId)
    if unit then
        local skill = Unit_getSkill(unit, skillId)
        return skill
    end
    return nil
end

function BattleLoop:targetSelectionNeeded(skillConfig)
    return SkillConfig_targetSelectionNeeded(Battle_SkillConfig, skillConfig)
end

function BattleLoop:getBattleLogicTime()
    if self.mBattleCore then
        local time = BattleCore_getCurrentTime(self.mBattleCore)
        return time
    end
    return 0
end

function BattleLoop:getAccumulator()
    return self.accumulator
end

function BattleLoop:getFastForwardFlag()
    return self.isFastForward
end

function BattleLoop:getIsRewind()
    return self.isRewind
end

function BattleLoop:isSingleMode()
    if self.mBattleCore then
        return BattleCore.isSingleMode(self.mBattleCore)
    end

    return false
end

function BattleLoop:checkGameOver()
    if not self.isGameOver then
        if self.currentState then
            local gameOverDelay = State_getGameOverDelay(self.currentState)
            if gameOverDelay > 1000 then
                local winTeamId = BattleCore.getWonTeamId(self.mBattleCore)
                local isEscapeBattle = State_isEscapeBattle(self.currentState)
                self:dispatchEvent(BattleLoop.Event_Game_Over,{winTeamId = winTeamId, isEscapeBattle = isEscapeBattle})
                self.isGameOver = true
            end

            if cc.isDead( self ) then
                return
            end
            local isBattleUIVisible = gameOverDelay < 500
            self:dispatchEvent(BattleLoop.Event_Set_BattleUI_Visible,{isVisible = isBattleUIVisible})
        end
    end
end

function BattleLoop:stop()
    self.isGameOver = true
    local winTeamId = BattleCore.getWonTeamId(self.mBattleCore)
    local isEscapeBattle = State_isEscapeBattle(self.currentState)
    local unit = self:getEntityById(self.mBattleModel:getControlledEntityId())
    local isWin = winTeamId == unit:teamId()
    local ownerDir = self.mBattleModel:getControlledEntity().dir
    local victoryDir = 1
    if isWin then
        victoryDir = ownerDir
    else
        if ownerDir == 1 then
            victoryDir = -1
        else
            victoryDir = 1
        end
    end
    local event = {isWin = isWin, victoryDir = victoryDir, isEscapeBattle = isEscapeBattle}
    self:dispatchEvent(BattleLoop.Event_Loop_End, event)
end

function BattleLoop:alive(id)
    if self.mBattleCore then
        return BattleCore.alive(self.mBattleCore,id)
    end
    return false
end

function BattleLoop:setAutoBattleInSingleMode(flag)
    if self.mBattleCore then
        local playerUnit = BattleCore.getUnitByUserId(self.mBattleCore, UD:getUid() or 0)
        if playerUnit then
            playerUnit:switchAutoBattle(flag, Constant.PlayerAutoBattleAI)
        end
    end
end



-- 设置单人战斗暂停状态
function BattleLoop:setBattlePause(b)
    if b then
        self:pause()
    else
        self:resume()
    end
end


return BattleLoop
